<?php
namespace Test\Server;
error_reporting(E_ALL);

require_once __DIR__ . '/../../Thrift/ClassLoader/ThriftClassLoader.php';
use Thrift\ClassLoader\ThriftClassLoader;

$genDir = __DIR__ .'/gen-php';

//注册以自动加载类，目录记得改为自己实际的目录，如果不想用自动加载类也可以将TestService.php和Types.php直接包含进来
$loader = new ThriftClassLoader();
$loader->registerNamespace('Thrift', __DIR__ . '/../../Thrift' );
$loader->registerNamespace('Server', __DIR__ . '/gen-php/Server' );
$loader->registerDefinition('ThriftGen', $genDir);
$loader->register();

/*
 * This is not a stand-alone server.  It should be run as a normal
 * php web script (like through Apache's mod_php) or as a cgi script
 * (like with the included runserver.py).  You can connect to it with
 * THttpClient in any language that supports it.  The PHP tutorial client
 * will work if you pass it the argument "--http".
 */

if(php_sapi_name() == 'cli')
{
    ini_set("display_errors", "stderr");
}

use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TPhpStream;
use Thrift\Transport\TBufferedTransport;
use Server\ThriftGen\Test\Service\TestServiceIf;
use Server\ThriftGen\Test\Service\TestServiceProcessor;
use Server\ThriftGen\Test\Entity\User;

class TestHandler implements TestServiceIf
{
    public function getUserName($userId)
    {
        return "test name";
    }
    public function getUserInfo($userId)
    {
        $user = new User();
        $user->userId=$userId;
        $user->userName="test name";
        return $user;
    }
    public function test($id)
    {
        echo "Start...\n";
        //休眠5秒模拟处理，http方式还是阻塞效果，socket方式才异步
        sleep(5);
        echo "End!!!\n";
    }
}

$http = new swoole_http_server( '127.0.0.1', 9091 );

// 动态资源
$http->on('request', function ($request, $response) {
    $handler = new TestHandler();
    $processor = new TestServiceProcessor($handler);

    $transport = new TBufferedTransport(new TPhpStream(TPhpStream::MODE_R | TPhpStream::MODE_W));
    $protocol = new TBinaryProtocol($transport, true, true);

    ob_start();
    $transport->open();
    $processor->process($protocol, $protocol);
    $transport->close();
    $ret2return = ob_get_contents();
    ob_end_clean();

    $response->header("Content-Type", "application/x-thrift");
    $response->end( $ret2return ); // 一次就结束 多次用write
});
